<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card shadow="hover">
      <el-button type="primary" @click="showAddCateDialogForm()"
        >添加分类</el-button
      >
      <!-- 用自定义标签渲染分类列表 -->
      <tree-table
        class="tree_table"
        :data="cateList"
        :columns="columns"
        :expand-type="false"
        :selection-type="false"
        :show-index="true"
        index-text="#"
        :show-row-hover="false"
        border
      >
        <template slot="isOk" slot-scope="scope">
          <i
            class="el-icon-success"
            v-if="scope.row.cat_deleted === false"
            style="color: #99d98c"
          ></i>
          <i class="el-icon-error" v-else style="color: #dc2f02"></i>
        </template>

        <template slot="goodsOrder" slot-scope="scope">
          <el-tag type="success" v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag type="warning" v-else-if="scope.row.cat_level === 1">二级</el-tag>
          <el-tag v-else="scope.row.cat_level === 2">三级</el-tag>
        </template>

        <template slot="options" slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            round
            icon="el-icon-edit"
            @click="showEditDialog(scope.row)"
            >编辑</el-button
          >
          <el-button
            type="danger"
            size="mini"
            round
            icon="el-icon-delete"
            @click="showDeleteDialog(scope.row)"
            >删除</el-button
          >
        </template>
      </tree-table>

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="goods_cate_query.pagenum"
        :page-sizes="[5, 10, 20, 30]"
        :page-size="goods_cate_query.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 点击添加分类的提示框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addCateDialogFormVisible"
      width="40%"
      @close="addCateDialogFormClosed()"
    >
      <el-form :model="addCateInfo" :rules="addCateRules" ref="addCateRef" label-width="100px">
        <el-form-item label="分类名称：" label-width="100px" prop="cat_name">
          <el-input
            v-model="addCateInfo.cat_name"></el-input>
        </el-form-item>

        <el-form-item label="父级分类：" label-width="100px">
          <el-cascader
            expand-trigger="hover"
            v-model="cascaderValue"
            :options="parentCateList"
            :props="cascaderProps"
            style="width: 100%"
            clearable
            @change="handleChange"
          >
          </el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addCateDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate()">确 定</el-button>
      </div>
    </el-dialog>

      <!-- 编辑提示框 -->     
      <el-dialog title="编辑分类信息" :visible.sync="editDialogVisible" width="40%" @close="editDialogClosed()">
      
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="120px"
      >
        <el-form-item label="分类名称：" prop="cat_name">
          <el-input v-model="editForm.cat_name" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="分类等级：">
          <el-input
            disabled
            v-model="editForm.cat_id"
            autocomplete="off"
          ></el-input>
        </el-form-item>

      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCate()">确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 删除提示框 -->
    <el-dialog
      title="删除分类"
      :visible.sync="delCateDialogFormVisible"
      width="40%">
      
      <el-form
        :model="deleteComfirmForm"
        ref="deleteFormRef"
        label-width="120px"
      >
        <el-form-item label="分类名称：">
          <el-input disabled v-model="deleteComfirmForm.cat_name"></el-input>
        </el-form-item>

        <el-form-item label="分类等级：">
          <el-input disabled v-model="deleteComfirmForm.cat_level" autocomplete="off"></el-input>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="delCateDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="deleteCate()">确 定</el-button>
      </span>
    </el-dialog>



  </div>
</template>

<script>
export default {
  created() {
    this.getGoodsCateList();
  },
  data() {
    return {
      cateList: [],
      goods_cate_query: {
        type: 3,
        pagenum: 1,
        pagesize: 5,
      },
      // 总数据个数
      total: 0,
      columns: [
        {
          label: "分类名称",
          prop: "cat_name",
        },
        {
          label: "是否有效",
          // 表示把当前列定义为模板列
          type: "template",
          // 表示当前列使用的自定义插槽名称
          template: "isOk",
        },
        {
          label: "等级",
          // 表示把当前列定义为模板列
          type: "template",
          // 表示当前列使用的自定义插槽名称
          template: "goodsOrder",
        },
        {
          label: "操作",
          // 表示把当前列定义为模板列
          type: "template",
          // 表示当前列使用的自定义插槽名称
          template: "options",
        },
        
      ],
      addCateDialogFormVisible: false,
      addCateInfo: {
        // 将要添加分类的名称
        cat_name: "",
        // 父级分类的id
        cat_pid: 0,
        // 分类的等级，默认要添加的是一级分类
        cat_level: 0,
      },
      addCateRules:{
        cat_name:[
          { required: true, message: "请输入商品分类名称", trigger: "blur"}
        ]
      },

      parentCateList: [],
      cascaderValue: [],
      // 指定级联选择器的配置对象
      cascaderProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
        checkStrictly:'true'
      },


      // 删除提示框相关属性
      delCateDialogFormVisible:false,
      deleteComfirmForm:{},

      // 编辑提示框相关属性
      editDialogVisible:false,
      editForm:{},
      editFormRules:{
        cat_name:[
          {required: true, message: "请输入分类名称", trigger: "blur"}
        ]
      },


    };
  },
  methods: {
    async getGoodsCateList() {
      const { data: res } = await this.$http.get("categories", {
        params: this.goods_cate_query,
      });
      // console.log(res);
      if (res.meta.status != 200)
        return this.$message.error("商品分类信息获取失败");
      this.cateList = res.data.result;
      this.total = res.data.total;
    },
    showEditDialog(row) {
      console.log(row);
      this.editDialogVisible = true;
      this.editForm = this.deepClone(row);
      this.editForm.cat_level = this.editForm.cat_level + 1;
    },

    showDeleteDialog(row) {
      this.delCateDialogFormVisible = true;
      this.deleteComfirmForm = this.deepClone(row);
      this.deleteComfirmForm.cat_level = this.deleteComfirmForm.cat_level + 1;
      // console.log(row);
      // console.log(this.deleteComfirmForm);
    },
    handleSizeChange(newSize) {
      this.goods_cate_query.pagesize = newSize;
      this.getGoodsCateList();
    },
    handleCurrentChange(newPageNum) {
      this.goods_cate_query.pagenum = newPageNum;
      this.getGoodsCateList();
    },
    showAddCateDialogForm() {
      this.getParentCate();
      this.addCateDialogFormVisible = true;
    },
    async getParentCate() {
      const { data: res } = await this.$http.get("categories", {
        params: { type: 2 },
      });
      if (res.meta.status !== 200)
        return this.$message.error("获取商品父级分类信息失败");
      this.parentCateList = res.data;
      // console.log(this.parentCateList);
    },
    addCate() {
      this.$refs.addCateRef.validate(async (valid)=>{
        if(!valid) return this.$message.error("添加分类信息校验失败");

        const {data:res} = await this.$http.post('categories', this.addCateInfo);
        if(res.meta.status !== 201) return this.$message.error("添加商品分类失败");

        this.getGoodsCateList();
        this.addCateDialogFormVisible = false;
        this.$message.success("添加商品分类成功");
      });
    },
    handleChange(value) {
      // console.log(this.cascaderValue);
      if(this.cascaderValue.length > 0){
        // 父级分类的 ID
        this.addCateInfo.cat_pid = this.cascaderValue[this.cascaderValue.length - 1];
        this.addCateInfo.cat_level = this.cascaderValue.length;
      }else{
        this.addCateInfo.cat_pid = 0;
        this.addCateInfo.cat_level = 0;
      }
    },
    addCateDialogFormClosed(){
      this.cascaderValue = [];
      this.$refs.addCateRef.resetFields();
      this.addCateInfo.cat_pid = 0;
      this.addCateInfo.cat_level = 0;
    },
    deepClone(target){
      let result;
      if(this.checkType(target) === 'Object'){
        result = {};
        for(let key in target){
          result[key] = this.deepClone(target[key]);
        }
      }else if(this.checkType(target) === 'Array'){
        result = [];
        for(let i = 0; i < target.length; i ++){
          result[i] = this.deepClone(target[i]);
        }
      }else if(this.checkType(target) === 'Function'){
        result = new Function('return ' + target.toString()).call(this);
      }else if(this.checkType(target) === 'Date'){
        result = new Date(target.valueOf());
      }else if(this.checkType(target) === 'RegExp'){
        result = new RegExp(target);
      }else if(this.checkType(target) === 'Map'){
        result = new Map();
        target.forEach((v, k) => {
          result.set(k, this.deepClone(v));
        })
      }else if(this.checkType(target) === 'Set'){
        result = new Set();
        for(let val of target.values()){
          result.add(this.deepClone(val));
        }
      }else{
        result = target;
      }
      return result;
    },
    checkType(target){
      return Object.prototype.toString.call(target).slice(8, -1);
    },
    async deleteCate(){
      const {data:res} = await this.$http.delete(`categories/${this.deleteComfirmForm.cat_id}`);
      if(res.meta.status !== 200) this.$message.error('删除分类失败');
      this.getGoodsCateList();
      this.delCateDialogFormVisible = false;
      this.$message.success("分类删除成功");
    },
    editDialogClosed(){
      this.$refs.editFormRef.resetFields();
    },
    editCate(){
      this.$refs.editFormRef.validate(async (valid) => {
        if(!valid) return this.$message.error('修改分类信息校验失败');
        const {data:res} = await this.$http.put(`categories/${this.editForm.cat_id}`, {cat_name: this.editForm.cat_name});
        if(res.meta.status !== 200) this.$message.error('分类信息编辑失败');
        this.editDialogVisible = false;
        this.getGoodsCateList();
        this.$message.success('修改分类信息成功');
      })
    }

  },
};
</script>

<style lang="less" scoped>
.tree_table {
  margin: 20px 0;
}

/////
.el-cascader-menu .el-radio {
  display: table;
  vertical-align: middle;
  width: 90%;
  height: 100%;
  position: absolute;
  box-sizing: border-box;
  margin-left:-20px;
  padding-left:10px;
}
.el-cascader-menu .el-radio .el-radio__input {
  display: table-cell;
  vertical-align: middle;
}

</style>
